<?php

namespace App\Http\Controllers;

use App\Http\Requests\type;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class TypeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $types = \App\Models\Type::paginate(10);
        return view('type.index', [
            'types' => $types
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return view('type.create', ['type' => null]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return Response
     */
    public function store(type $request)
    {
        $validate = $request->validated();
        $type = new \App\Models\Type();
        $validate['user_id'] = Auth::user()->id ?? 1;
        $type->create($validate);
        return redirect()->route('type.index')->with('success', '添加分类成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        dd(66);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param \App\Models\Type $type
     * @param int $id
     * @return void
     */
    public function edit(\App\Models\Type $type)
    {
        return view('type.create', ['type' => $type]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param type $request
     * @param \App\Models\Type $type
     * @return void
     */
    public function update(type $request, \App\Models\Type $type)
    {
        $validate = $request->validated();
        $res = $type->update($validate);
        return redirect()->route('type.index')->with(  $res ? 'success' : 'danger',   $res ? '编辑分类成功' : '编辑分类失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $type = \App\Models\Type::find($id);
        // 分类存在接口关联， 不允许删除！
        if (!$type || $type->articles->isNotEmpty()) return \response()->json(['code' => 301, 'msg' => "当前分类存在接口数据，请先删除接口数据再删除分类"]);
        $type->delete();
        return \response()->json(['code' => 200, 'msg' => "删除成功"]);
    }

}
